import {
  Controller,
  Post,
  Get,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
  Headers,
  BadRequestException,
} from '@nestjs/common';
import { PaymentService } from './payment.service';
import { WechatPayService } from './wechat-pay.service';
import { AlipayService } from './alipay.service';
import { OrdersService } from '../orders/orders.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CreatePaymentDto } from './dto/create-payment.dto';

@Controller('payment')
export class PaymentController {
  constructor(
    private readonly paymentService: PaymentService,
    private readonly wechatPayService: WechatPayService,
    private readonly alipayService: AlipayService,
    private readonly ordersService: OrdersService,
  ) {}

  /**
   * 创建支付
   */
  @Post('create')
  @UseGuards(JwtAuthGuard)
  async createPayment(@Body() createPaymentDto: CreatePaymentDto) {
    return await this.paymentService.createPayment(createPaymentDto);
  }

  /**
   * 查询支付状态
   */
  @Get('query/:orderNo')
  @UseGuards(JwtAuthGuard)
  async queryPayment(
    @Param('orderNo') orderNo: string,
    @Query('method') method: string,
  ) {
    return await this.paymentService.queryPayment(orderNo, method);
  }

  /**
   * 手动同步订单状态（用于修复已支付但未更新的订单）
   */
  @Post('sync/:orderNo')
  @UseGuards(JwtAuthGuard)
  async syncOrderStatus(
    @Param('orderNo') orderNo: string,
    @Query('method') method: string,
  ) {
    console.log('\x1b[36m\n========== 🔄 手动同步订单状态 ==========\x1b[0m');
    console.log('📦 订单号:', orderNo);
    console.log('💳 支付方式:', method);

    return await this.paymentService.queryPayment(orderNo, method);
  }

  /**
   * 批量同步当前用户的所有待支付订单
   */
  @Post('sync-all')
  @UseGuards(JwtAuthGuard)
  async syncAllOrders(@Request() req: any) {
    const userId = req.user.id;
    console.log('\x1b[36m\n========== 🔄 批量同步用户订单 ==========\x1b[0m');
    console.log('👤 用户ID:', userId);

    try {
      // 获取用户所有pending状态的订单
      const orders = await this.ordersService.findByUser(userId);
      const pendingOrders = orders.filter(order => order.status === 'pending');

      console.log('📦 待同步订单数:', pendingOrders.length);

      const results = [];

      for (const order of pendingOrders) {
        console.log(`\n🔄 同步订单: ${order.orderNo}`);
        
        try {
          // 查询并自动更新
          const result = await this.paymentService.queryPayment(
            order.orderNo,
            order.paymentMethod === 'wechat' ? 'wechat_native' : 'alipay_page'
          );

          results.push({
            orderNo: order.orderNo,
            success: true,
            status: result.trade_state || result.tradeStatus,
          });
        } catch (error) {
          console.error(`❌ 同步订单 ${order.orderNo} 失败:`, error.message);
          results.push({
            orderNo: order.orderNo,
            success: false,
            error: error.message,
          });
        }
      }

      console.log('\x1b[36m========== ✅ 批量同步完成 ==========\n\x1b[0m');

      return {
        total: pendingOrders.length,
        results,
      };
    } catch (error) {
      console.error('\x1b[31m========== ❌ 批量同步失败 ==========\x1b[0m');
      console.error(error);
      throw error;
    }
  }

  /**
   * 微信支付回调（直接从微信接收 - 如果在本项目配置了回调）
   */
  @Post('wechat/notify')
  async wechatNotify(@Headers() headers: any, @Body() body: any) {
    console.log('\x1b[32m\n========== 📱 微信支付回调（直接）==========\x1b[0m');
    console.log('\x1b[32m⏰ 时间:\x1b[0m', new Date().toISOString());
    console.log('\x1b[32m📨 Headers:\x1b[0m', JSON.stringify(headers, null, 2));
    console.log('\x1b[32m📦 Body:\x1b[0m', JSON.stringify(body, null, 2));

    try {
      const result = await this.wechatPayService.handleNotify(headers, body);

      if (!result.isValid) {
        console.error('❌ 签名验证失败');
        throw new BadRequestException('签名验证失败');
      }

      console.log('\x1b[32m✅ 签名验证通过\x1b[0m');
      console.log('\x1b[32m📋 回调数据:\x1b[0m', {
        订单号: result.outTradeNo,
        支付状态: result.tradeState,
        交易号: result.transactionId,
        支付金额: result.totalAmount,
        支付时间: result.paidAt,
      });

      // 更新订单状态
      if (result.outTradeNo && result.tradeState === 'SUCCESS') {
        console.log('\x1b[32m🔄 开始处理订单支付成功...\x1b[0m');
        
        await this.ordersService.handlePaymentSuccess({
          orderNo: result.outTradeNo,
          transactionId: result.transactionId!,
          paymentMethod: 'wechat',
          paidAt: result.paidAt!,
          paidAmount: result.totalAmount!,
        });

        console.log('\x1b[32m🎉 订单处理完成！\x1b[0m');
      } else {
        console.log('\x1b[33m⚠️ 支付状态非SUCCESS，不处理订单\x1b[0m');
      }

      console.log('\x1b[32m========== ✅ 回调处理完成 ==========\n\x1b[0m');

      // 返回成功响应给微信
      return {
        code: 'SUCCESS',
        message: '成功',
      };
    } catch (error) {
      console.error('========== ❌ 回调处理失败 ==========');
      console.error('错误:', error);
      console.error('错误堆栈:', error.stack);
      throw error;
    }
  }

  /**
   * 微信支付回调（从代码小库转发过来）
   * 
   * 工作原理：
   * 1. 微信发送回调到代码小库（主回调地址）
   * 2. 代码小库判断订单号前缀（DTH开头）
   * 3. 转发到本接口进行处理
   * 
   * 注意：这个端点需要能处理来自代码小库的转发请求
   */
  @Post('wechat/callback')
  async wechatCallback(@Headers() headers: any, @Body() body: any) {
    console.log('\x1b[32m🔄 收到微信支付回调（转发）\x1b[0m');
    console.log('\x1b[32mHeaders:\x1b[0m', headers);
    console.log('\x1b[32mBody:\x1b[0m', body);

    try {
      // 验证签名（使用相同的微信配置）
      const result = await this.wechatPayService.handleNotify(headers, body);

      if (!result.isValid) {
        console.error('❌ 签名验证失败');
        throw new BadRequestException('签名验证失败');
      }

      console.log('\x1b[32m✅ 签名验证通过\x1b[0m');
      console.log('\x1b[32m📦 订单号:\x1b[0m', result.outTradeNo);
      console.log('\x1b[32m💰 支付状态:\x1b[0m', result.tradeState);
      console.log('\x1b[32m💵 支付金额:\x1b[0m', result.totalAmount);

      // 更新订单状态
      if (result.outTradeNo && result.tradeState === 'SUCCESS') {
        await this.ordersService.handlePaymentSuccess({
          orderNo: result.outTradeNo,
          transactionId: result.transactionId!,
          paymentMethod: 'wechat',
          paidAt: result.paidAt!,
          paidAmount: result.totalAmount!,
        });

        console.log('\x1b[32m🎉 订单支付成功，已更新状态\x1b[0m');
      }

      return {
        code: 'SUCCESS',
        message: '成功',
      };
    } catch (error) {
      console.error('❌ 处理回调失败:', error);
      console.error('错误详情:', error.message);
      
      // 返回失败响应
      return {
        code: 'FAIL',
        message: error.message || '处理失败',
      };
    }
  }

  /**
   * 支付宝支付回调
   */
  @Post('alipay/notify')
  async alipayNotify(@Body() body: any) {
    console.log('💰 收到支付宝支付回调');
    console.log('Body:', body);

    const result = await this.alipayService.handleNotify(body);

    if (!result.isValid) {
      return 'fail';
    }

    // 更新订单状态
    if (
      result.outTradeNo &&
      (result.tradeStatus === 'TRADE_SUCCESS' ||
        result.tradeStatus === 'TRADE_FINISHED')
    ) {
      await this.ordersService.handlePaymentSuccess({
        orderNo: result.outTradeNo,
        transactionId: result.tradeNo!,
        paymentMethod: 'alipay',
        paidAt: new Date(),
        paidAmount: result.totalAmount!,
      });
    }

    // 返回成功响应给支付宝
    return 'success';
  }

  /**
   * 支付宝支付同步回调
   */
  @Get('alipay/return')
  async alipayReturn(@Query() query: any) {
    console.log('💰 支付宝同步回调:', query);
    
    const result = await this.alipayService.handleNotify(query);
    
    if (result.isValid && result.outTradeNo) {
      // 重定向到订单结果页
      return {
        redirect: `/order/result?orderNo=${result.outTradeNo}`,
      };
    }
    
    return {
      redirect: '/order/result?status=failed',
    };
  }
}




